var id;
var result;
var isAnimating = false;

//动画函数
function animate() {
    id = requestAnimationFrame(animate);
    result = TWEEN.update();
    if(!result) cancelAnimationFrame(id);
}

var target1 = document.getElementById('target1');
var target2 = document.getElementById('target2');
var oBtnStart = document.getElementById('start');
var oBtnEnd = document.getElementById('end');

var tween1 = new TWEEN.Tween(target1.dataset)
            .to({
                x: 500
            }, 2000)
            .easing(TWEEN.Easing.Elastic.InOut)
            .delay(1000)
            .onUpdate(function(obj) {
                target1.style.left = obj.x + 'px';
            })
            .onComplete(function(obj) {
                obj.x = 0;
                target1.style.left = obj.x + 'px';
            })

var tween2 = new TWEEN.Tween(target2.dataset)
            .to({
                x: 300
            }, 3000)
            .easing(TWEEN.Easing.Elastic.InOut)
            .delay(500)
            .onUpdate(function(obj) {
                target2.style.left = obj.x + 'px';
            })
            .onComplete(function(obj) {
                obj.x = 0;
                target2.style.left = obj.x + 'px';
            })

tween1.chain(tween2);
tween2.chain(tween1);

oBtnStart.addEventListener('click', function(e) {
    var event = e || window.event;
    if(!isAnimating) {
        tween1.start();
        animate();
    }
    isAnimating = true;
})

oBtnEnd.addEventListener('click', function(e) {
    var event = e || window.event;
    if(isAnimating) {
        tween1.stop();
        cancelAnimationFrame(id);
    }
    isAnimating = false;
})